package com.innovation.chengzhangriji;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Process;
import android.util.DisplayMetrics;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.orhanobut.logger.LogLevel;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.Settings;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.xiaomi.mipush.sdk.MiPushClient;

import java.util.List;

public class ChZhRJApplication extends Application implements Application.ActivityLifecycleCallbacks {

    private static final String TAG = "成长日记";

    private IWXAPI mWeiXinApi;

    private Typeface mTypeface;

    public void setActivityLive(int activityLive) {
        this.activityLive = activityLive;
    }

    private int activityLive = 0;

    private static ConfigurationManager sConfigurationManager;

//    private RefWatcher refWatcher;

//    public static RefWatcher getRefWatcher(Context context) {
//        ChZhRJApplication application = (ChZhRJApplication) context.getApplicationContext();
//        return application.refWatcher;
//    }

    @Override
    public void onCreate() {
        registerActivityLifecycleCallbacks(this);
        setStetho();
        setupLog();
        setupUmeng();
        initApi();
        setupImageLoader();
        loadTypeface();
        logInformation();
        super.onCreate();
        // 检测内存溢出
//        refWatcher = LeakCanary.install(this);
    }

    public void initApi() {
        setupWeiXin();
        registerMiPush();
    }

    /**
     * 获得微信API
     */
    public IWXAPI getWeiXinApi() {
        return mWeiXinApi;
    }

    /**
     * 获得字体
     */
    public Typeface getTypeface() {
        return mTypeface;
    }

    /**
     * 应用是否活着
     *
     * @return 是否存在
     */
    public boolean isApplicationLive() {
        return activityLive != 0;
    }

    // 设置调试
    private void setStetho() {
        /*if (BuildConfig.DEBUG) {
            Stetho.initialize(Stetho.newInitializerBuilder(this)
                    .enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
                    .enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this))
                    .build());
        }*/
    }

    // 设置打印信息
    private void setupLog() {
        Settings settings = Logger.init(TAG);
        if (BuildConfig.DEBUG) {
            settings.setLogLevel(LogLevel.FULL);
        } else {
            settings.setLogLevel(LogLevel.NONE);
        }
    }

    // 设置友盟的统计方式
    private void setupUmeng() {
        // 禁止默认的页面统计方式
        MobclickAgent.openActivityDurationTrack(false);
    }

    // 设置图片加载配置
    private void setupImageLoader() {
        ImageLoaderConfiguration config;
        // TODO 未来考虑优化设置,暂时采用默认设置.
        config = ImageLoaderConfiguration.createDefault(this);
        ImageLoader.getInstance().init(config);
    }

    // 设置微信
    private void setupWeiXin() {
        mWeiXinApi = WXAPIFactory.createWXAPI(this, Config.getConfig(ConfigurationManager.WX_ID), true);
        mWeiXinApi.registerApp(Config.getConfig(ConfigurationManager.WX_ID));
    }

    // 加载字体
    private void loadTypeface() {
        // mTypeface = Typeface.createFromAsset(getAssets(), Config.CUTE_FONTS);
        mTypeface = Typeface.DEFAULT;
    }

    private void logInformation() {
        if (BuildConfig.DEBUG) {
            DisplayMetrics dm = getResources().getDisplayMetrics();
            // 屏幕密度
            Logger.d("屏幕密度" + dm.density);
            // 每英寸的像素
            Logger.d("每英寸的像素" + dm.densityDpi);
        }
    }

    // 注册小米推送
    private void registerMiPush() {
        if (shouldInit()) {
            MiPushClient.registerPush(this, Config.getConfig(ConfigurationManager.MIPUSH_APP_ID), Config.getConfig(ConfigurationManager.MIPUSH_APP_KEY));
        }
    }

    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
//        activityLive++;
    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {
//        if(activityLive == 0) {
//            activityLive++;
//        }
        activityLive++;
    }

    @Override
    public void onActivityPaused(Activity activity) {
        activityLive--;
    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
//        activityLive--;
    }
}
